package com.apptonelabs.android.view;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.apptonelabs.android.R;
import com.apptonelabs.android.controller.PNREntryActivity;
import com.apptonelabs.android.controller.PNRStatusCrawller;
import com.apptonelabs.android.model.PNREntryList;
import com.apptonelabs.android.model.PNRResponse;
import com.apptonelabs.android.model.PNRStatus;
import com.apptonelabs.android.model.PNRType;
import com.apptonelabs.android.model.PassengerDetails;
import com.google.gson.Gson;

public class PNRArrayAdapter extends ArrayAdapter<PNRStatus> {
	private final Context context;
	private final List<PNRStatus> values;
	private final PNRType type;

	public PNRArrayAdapter(Context context, List<PNRStatus> values,PNRType type) {
		super(context, R.layout.pnrlist, values);
		this.context = context;
		this.values = values;
		this.type = type;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View rowView = inflater.inflate(R.layout.pnrlist, parent, false);
		TextView textView = (TextView) rowView.findViewById(R.id.pnrLableTV);
		TextView textView2 = (TextView) rowView.findViewById(R.id.pnrLableTV2);
		ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
		
		// Position == 0 should be the Title of the Activity
		if(position == 0) {
			parent.setBackgroundColor(Color.parseColor("#000000"));
			
			// Font settings
			textView.setTextSize(18F);
			textView2.setTextSize(16F);

			imageView.setImageResource(R.drawable.ic_launcher);
			String text = "<font color=#ffffff><b>Indian Railway PNR Status</b></font>";
			textView.setText(Html.fromHtml(text));
			if(PNRType.FUTURE == type) {
				textView2.setText("You have " + (this.values.size()-1) + " up coming Journeys.");
			} else if(PNRType.PAST == type) {
				textView2.setText("You travelled " + (this.values.size()-1) + " times!!!");
			} else {
				textView2.setText("Today, you have " + (this.values.size()-1) + " Journeys.");
			}
			return rowView;
		}

		// Font settings
		textView.setTextSize(16F);
		textView2.setTextSize(16F);
		
		// Text
		String text = 
				"<b>"
				+ "<font color=#eeeeee>"
				+ values.get(position).getTrainDetails().getBoardingDate()
				+ "</font>"
				+ " <font color=#6aff6a>"
				+ "&nbsp;&nbsp;" + values.get(position).getPnr()
				+ "</font>"
				+ " <font color=#eeeeee>"
				+ "&nbsp;&nbsp;" + values.get(position).getTrainDetails().getReservedType()
				+ "</font>"
				+ "</b>"
				;
		
		textView.setText(Html.fromHtml(text));
		
		
		textView2.setText(
				"Train#: " + values.get(position).getTrainDetails().getNumber().substring(1,
						values.get(position).getTrainDetails().getNumber().length())
				+ ",  "
				+ values.get(position).getTrainDetails().getFrom().trim()
				+ " -> "
				+ values.get(position).getTrainDetails().getTo().trim()
				+ ",  @ "
				+ values.get(position).getTrainDetails().getBoardingPoint()
						.trim());

		// Change icon based on name
		String br = values.get(position).getPassengerDetails().get(0)
				.getCurrentStatus();

		String cs = values.get(position).getTrainDetails().getChatStatus();

		if (br.startsWith("CNF") || br.startsWith("RAC")
				|| br.startsWith("Can")) {
			imageView.setImageResource(R.drawable.cnf);
		} else if (br.startsWith("W")
				&& cs.equalsIgnoreCase("CHART NOT PREPARED")) {
			imageView.setImageResource(R.drawable.wlo);
		} else if (br.startsWith("W")
				&& !cs.equalsIgnoreCase("CHART NOT PREPARED")) {
			imageView.setImageResource(R.drawable.wlr);
		} else {
			imageView.setImageResource(R.drawable.cnf);
		}

		rowView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showPNRDetails(position);
			}
		});
		
		return rowView;
	}
	
	private void showPNRDetails(final int position) {
		// try to get the latest Status
		String mPhoneNumber = null;
		// Read Phone Number
		try {
			TelephonyManager tMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			mPhoneNumber = tMgr.getDeviceId();
			
			if(mPhoneNumber == null || mPhoneNumber.trim() == "") {
				mPhoneNumber = null;
			}
		} catch (Exception e) {
			// ignore
		}

		// Proceed further
		PNRStatus backup = values.get(position);
		PNRStatus pnrStatus = values.get(position);
		String br = values.get(position).getPassengerDetails().get(0)
				.getCurrentStatus();

		if(pnrStatus.getTrainDetails().getChatStatus().equalsIgnoreCase("CHART NOT PREPARED") &&
				(this.type == PNRType.TODAY || this.type == PNRType.FUTURE) &&
				(br.contains("CNF") || br.contains("WL") || br.contains("RAC"))) {
			// Connect to the Server and Get the PNR status
			try {
				String pnr1 = pnrStatus.getPnr(); // "1154177041";
				PNRStatusCrawller check = new PNRStatusCrawller();
				
				String uri = "http://1-dot-pnr-enquiry.appspot.com/pnr?pnr=" + pnr1;
				if(mPhoneNumber != null && mPhoneNumber.trim().length() > 0) {
					uri = uri + ("&m=" + mPhoneNumber);
				}
				
				String data = check.getPNRResponse(uri);
				if(data != null) {
					Gson gson = new Gson();
					PNRResponse res = gson.fromJson(data, PNRResponse.class);
					pnrStatus = res.getStatus();
					if(pnrStatus != null) {
						pnrStatus.setPnr(pnr1);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		if(pnrStatus != null && pnrStatus.getTrainDetails() != null && pnrStatus.getTrainDetails().getName() != null) {
			// proceeed
		} else {
			pnrStatus = backup;
		}

		List<String> list = new ArrayList<String>();
		PNREntryList obj = new PNREntryList();
		try {
			Intent to = null;
			Bundle bundle = new Bundle();
			list.add("Title");
			list.add("<b>PNR Number	&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:&nbsp;</b> " + pnrStatus.getPnr());
			list.add("<b>Chart Status &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:&nbsp;</b> " + pnrStatus.getTrainDetails().getChatStatus());
			list.add("<b>Journey Date &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:&nbsp;</b> " + pnrStatus.getTrainDetails().getBoardingDate());
			list.add("<b>Train Name &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:&nbsp;</b> " + pnrStatus.getTrainDetails().getName());
			list.add("<b>Train number &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:&nbsp;</b> " + pnrStatus.getTrainDetails().getNumber().substring(1,
					pnrStatus.getTrainDetails().getNumber().length()));
			list.add("<b>Current status	&nbsp;&nbsp;&nbsp;:&nbsp;</b> " + pnrStatus.getPassengerDetails().get(0).getCurrentStatus());
			list.add("<b>Train from	&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:&nbsp;</b> " + pnrStatus.getTrainDetails().getFrom());
			list.add("<b>Train to &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:&nbsp;</b> " + pnrStatus.getTrainDetails().getTo());
			list.add("<b>Boradring point &nbsp;:&nbsp;</b> " + pnrStatus.getTrainDetails().getBoardingPoint());
			list.add("<b>Reservation up to :&nbsp;</b> " + pnrStatus.getTrainDetails().getReservedUpto());
			list.add("<b>Passengers&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Booked &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Current status</b>");
			for(PassengerDetails pd : pnrStatus.getPassengerDetails()) {
				list.add(pd.getName() + " &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + pd.getBookingStatus() + " &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; " + pd.getCurrentStatus());
			}

			obj.setList(list);
			
			bundle.putSerializable("pnrlist", obj);
			bundle.putSerializable("pnrlisttype", type);

			to = new Intent(this.getContext(), PNREntryActivity.class);
			to.putExtras(bundle);
			this.getContext().startActivity(to);
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

}